package com.se.domain.vo;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.se.domain.mysql.QuestionDO;
import com.se.domain.request.param.QParam;
import com.se.enums.ResultCode;
import com.se.exception.ResultException;
import lombok.Data;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Data
public class QVO {
    @JsonProperty("qId")
    Long qId;
    String title;
    Byte type;
    List<OptionVO> options = new LinkedList<>();
    String ans;

    public QVO(QParam qParam) {
        this.title = qParam.getTitle();
        this.type = qParam.getType();
        if(qParam.getOptions() != null){
            for (String option : qParam.getOptions()) {
                this.options.add(new OptionVO(option));
            }
        }
    }

    public QVO(QuestionDO questionDO) {
        this.qId = questionDO.getQId();
        this.title = questionDO.getTitle();
        this.type = questionDO.getType();
    }

    public void checkAns(String ans) throws ResultException {
        if(StrUtil.isBlank(ans)){
            throw new ResultException(ResultCode.QN_INVALID.getCode(), "有必填项答案为空");
        }

        if(this.type == QuestionDO.Type.SINGLE || this.type == QuestionDO.Type.MULTI){
            List<Long> oIds = Arrays.stream(ans.split(",")).map(Long::parseLong).toList();
            if(oIds.isEmpty()){
                throw new ResultException(ResultCode.QN_INVALID.getCode(), "选择题没有填写选项");
            }
            if(this.type == QuestionDO.Type.SINGLE){
                if(oIds.size() != 1){
                    throw new ResultException(ResultCode.QN_INVALID.getCode(), "单选题选了多个选项");
                }
            }

            for (Long oId : oIds) {
                boolean flag = false;
                for (OptionVO optionVO : this.options) {
                    if(Objects.equals(oId, optionVO.oId)){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    throw new ResultException(ResultCode.QN_INVALID.getCode(), "选择题选项不在范围中");
                }
            }
        }

    }
}
